package ltd.qisi.autoguipilot

import android.animation.Animator
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Intent
import android.graphics.PixelFormat
import android.hardware.display.DisplayManager
import android.os.IBinder
import android.util.Log
import android.util.TypedValue
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.widget.FrameLayout
import com.airbnb.lottie.LottieAnimationView


class BridgeService : Service() {
    // 获取WindowManager并添加视图
    private lateinit var windowManager: WindowManager
    private lateinit var floatingView: View
    private lateinit var rippleAnimation:LottieAnimationView
    private lateinit var borderView: View
    private lateinit var borderAnimation:LottieAnimationView
    override fun onCreate() {
        super.onCreate()
        val userId = android.os.Process.myUid() / 100000
        var displayId = 0
        if(userId == 10) {
            displayId = 0
        } else if(userId == 11){
            displayId = 1
        }

        // 获取 DisplayManager
        val displayManager = getSystemService(DISPLAY_SERVICE) as DisplayManager


        // 获取指定的显示屏
        val targetDisplay = displayManager.getDisplay(displayId)

        if (targetDisplay == null) {
            Log.e("WindowManager", "Display with id $displayId not found")
            throw RuntimeException("Display with id $displayId not found")
        }
        // 创建与目标显示屏关联的 Context
        val displayContext = createDisplayContext(targetDisplay)

        // 获取目标显示屏的 WindowManager
        windowManager = displayContext.getSystemService(WINDOW_SERVICE) as WindowManager

        // 创建悬浮窗视图
        floatingView =
            LayoutInflater.from(this).inflate(R.layout.layout_floating_window, null)
        rippleAnimation = floatingView.findViewById(R.id.rippleAnimation)

        // 创建悬浮窗视图
        borderView =
            LayoutInflater.from(this).inflate(R.layout.layout_border, FrameLayout(this))
        borderAnimation = borderView.findViewById(R.id.rippleAnimation)
    }

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        setForeground()
        intent?.apply {
            action?.let {
                if (it == "ACTION_SHOW_RIPPLE") {
                    val x = extras?.getInt("x", 0)
                    val y = extras?.getInt("y", 0)
                    Log.i("wangzhenghui","x = $x , y = $y")
                    showTapAnimation(x, y)
                } else if(it == "ACTION_SHOW_BORDER") {
                    showBorderAnimation()
                } else if(it == "ACTION_HIDE_BORDER") {
                    stopBorderAnimation()
                }
            }
        }
        return super.onStartCommand(intent, flags, startId)
    }

    private fun showTapAnimation(x: Int?, y: Int?) {

        rippleAnimation.progress = 0f
        rippleAnimation.playAnimation()
        rippleAnimation.setMaxProgress(0.5f)

        rippleAnimation.addAnimatorListener(object : Animator.AnimatorListener {
            override fun onAnimationStart(animation: Animator) {
                Log.i("wangzhenghui", "onAnimationStart")
            }

            override fun onAnimationEnd(animation: Animator) {
                Log.i("wangzhenghui", "onAnimationEnd")
                windowManager.removeView(floatingView)
            }

            override fun onAnimationCancel(animation: Animator) {
                Log.i("wangzhenghui", "onAnimationCancel")
            }

            override fun onAnimationRepeat(animation: Animator) {
                Log.i("wangzhenghui", "onAnimationRepeat")
            }

        })
        // 设置悬浮窗参数
        val params = WindowManager.LayoutParams(
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.WRAP_CONTENT,
            2024,
            WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS or WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN,
            PixelFormat.TRANSPARENT
        )

        params.gravity = Gravity.TOP or Gravity.START
        if (x != null && y != null) {
            params.x = x - (200.dpToPx()/2)
            params.y = y - (200.dpToPx()/2)
            Log.i("wangzhenghui","params.x = ${params.x}")
            Log.i("wangzhenghui","params.y = ${params.y}")
        } else {
            params.x = 0
            params.y = 100
        }



        windowManager.addView(floatingView, params)

    }

    private fun showBorderAnimation() {

        borderView.apply {
            isClickable = false
            isFocusable = false
            isFocusableInTouchMode = false
        }
        // 设置悬浮窗参数
        val params = WindowManager.LayoutParams(
            WindowManager.LayoutParams.MATCH_PARENT,
            WindowManager.LayoutParams.MATCH_PARENT,
            2024,
            WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL or WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE or WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS or WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN,
            PixelFormat.TRANSPARENT
        )

        params.gravity = Gravity.TOP or Gravity.START

        params.x = 0
        params.y = 0

        windowManager.addView(borderView, params)
    }

    private fun stopBorderAnimation() {
        windowManager.removeView(borderView)
    }

    // Float dp 转 px
    fun Float.dpToPx(): Float {
        return TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP,
            this,
            this@BridgeService.resources.displayMetrics
        )
    }

    // Int dp 转 px
    fun Int.dpToPx(): Int {
        return TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP,
            this.toFloat(),
            this@BridgeService.resources.displayMetrics
        ).toInt()
    }
    private fun setForeground() {
        try {
            val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
            val channel =
                NotificationChannel("autoGuiPilot", "autoGuiPilot", NotificationManager.IMPORTANCE_HIGH)
            notificationManager.createNotificationChannel(channel)
            val builder = Notification.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("autoGuiPilot")
                .setContentText("autoGuiPilot")
            //设置Notification的ChannelID,否则不能正常显示
            builder.setChannelId("autoGuiPilot")
            val notification = builder.build()
            startForeground(1000, notification)
        } catch (e: Exception) {
            Log.i("BridgeService",e.toString())
        }
    }
}